'use strict';
const db = uniCloud.database();
const rooms = db.collection('rooms');
const gameRecords = db.collection('game_records');

exports.main = async (event, context) => {
  const { action, data } = event;
  
  switch (action) {
    case 'create':
      return await createRoom(data);
    case 'join':
      return await joinRoom(data);
    case 'getRoom':
      return await getRoom(data);
    case 'getRecords':
      return await getRecords(data);
    case 'addRecord':
      return await addRecord(data);
    case 'settleRoom':
      return await settleRoom(data);
    default:
      return {
        code: -1,
        msg: '未知操作'
      };
  }
};

// 创建房间
async function createRoom(data) {
  const { roomId, userInfo } = data;
  
  try {
    // 获取测试用户信息
    const testUser = await db.collection('users').where({
      openId: 'test_user'
    }).get();
    
    if (testUser.data.length === 0) {
      console.error('测试用户不存在');
      return {
        code: -1,
        msg: '系统错误'
      };
    }
    
    // 检查房间号是否存在
    const existRoom = await rooms.where({
      roomId: roomId
    }).get();
    
    if (existRoom.data.length > 0) {
      return {
        code: -1,
        msg: '房间号已存在'
      };
    }
    
    // 创建房间时包含创建者和测试用户
    const roomData = {
      roomId,
      ownerOpenId: userInfo.openId,
      ownerName: userInfo.nickName,
      createTime: Date.now(),
      updateTime: Date.now(),
      status: 0,
      members: [
        {
          openId: userInfo.openId,
          nickname: userInfo.nickName,
          avatar: userInfo.avatarUrl,
          score: 0,
          joinTime: Date.now()
        },
        // 自动加入测试用户
        {
          openId: testUser.data[0].openId,
          nickname: testUser.data[0].userNick,
          avatar: testUser.data[0].avatar,
          score: 0,
          joinTime: Date.now()
        }
      ]
    };
    
    const result = await rooms.add(roomData);
    
    return {
      code: 0,
      msg: '创建成功',
      data: {
        ...roomData,
        _id: result.id
      }
    };
  } catch (e) {
    console.error(e);
    return {
      code: -1,
      msg: '创建失败'
    };
  }
}

// 加入房间
async function joinRoom(data) {
  const { roomId, userInfo } = data;
  
  try {
    const room = await rooms.where({
      roomId: roomId,
      status: 0
    }).get();
    
    if (room.data.length === 0) {
      return {
        code: -1,
        msg: '房间不存在或已结束'
      };
    }
    const roomData = room.data[0];
    // 检查是否已在房间中
    const isMember = roomData.members.some(member => member.openId === userInfo.openId);
    if (isMember) {
      return {
        code: 0,
        msg: '已在房间中',
        data: roomData
      };
    }
    
    // 添加新成员
    const newMember = {
      openId: userInfo.openid,
      nickname: userInfo.nickName,
      avatar: userInfo.avatarUrl,
      score: 0,
      joinTime: Date.now()
    };
    
    await rooms.doc(roomData._id).update({
      members: db.command.push([newMember]),
      updateTime: Date.now()
    });
    
    roomData.members.push(newMember);
    
    return {
      code: 0,
      msg: '加入成功',
      data: roomData
    };
  } catch (e) {
    console.error(e);
    return {
      code: -1,
      msg: '加入失败'
    };
  }
}

// 获取房间信息
async function getRoom(data) {
  const { roomId } = data;
  console.log('获取房间信息，roomId:', roomId);
  
  try {
    const result = await rooms.where({
      roomId: roomId,
      status: 0  // 只获取未结算的房间
    }).get();
    
    console.log('查询结果:', result);
    
    if (result.data.length === 0) {
      return {
        code: -1,
        msg: '房间不存在或已结束'
      };
    }
    
    // 获取房间的游戏记录
    const records = await gameRecords
      .where({
        roomId: roomId,
        status: 0
      })
      .orderBy('createTime', 'desc')
      .get();
    
    return {
      code: 0,
      msg: '获取成功',
      data: {
        ...result.data[0],
        records: records.data
      }
    };
  } catch (e) {
    console.error('获取房间信息失败:', e);
    return {
      code: -1,
      msg: '获取房间信息失败'
    };
  }
}

// 获取房间游戏记录
async function getRecords(data) {
  const { roomId, page = 1, pageSize = 20 } = data;
  console.log('获取游戏记录，参数:', data);
  
  try {
    const records = await gameRecords
      .where({
        roomId: roomId,
        status: 0
      })
      .orderBy('createTime', 'desc')
      .skip((page - 1) * pageSize)
      .limit(pageSize)
      .get();
    
    return {
      code: 0,
      data: records.data
    };
  } catch (e) {
    console.error('获取游戏记录失败:', e);
    return {
      code: -1,
      msg: '获取游戏记录失败'
    };
  }
}

// 添加支付记录
async function addRecord(data) {
  const { roomId, payerOpenid, payeeOpenid, amount } = data;
  
  try {
    // 获取房间信息
    const room = await rooms.where({
      roomId: roomId,
      status: 0
    }).get();
    
    if (room.data.length === 0) {
      return {
        code: -1,
        msg: '房间不存在或已结束'
      };
    }
    
    const roomData = room.data[0];
    
    // 更新成员积分
    const updatedMembers = roomData.members.map(member => {
      if (member.openId === payerOpenid) {
        return {
          ...member,
          score: member.score - amount
        };
      }
      if (member.openId === payeeOpenid) {
        return {
          ...member,
          score: member.score + amount
        };
      }
      return member;
    });
    
    // 添加支付记录
    const recordData = {
      roomId,
      payerOpenid,
      payerName: roomData.members.find(m => m.openId === payerOpenid).nickname,
      payeeOpenid,
      payeeName: roomData.members.find(m => m.openId === payeeOpenid).nickname,
      amount,
      createTime: Date.now(),
      status: 0
    };
    
    // 使用事务确保数据一致性
    const transaction = await db.startTransaction();
    try {
      await transaction.collection('rooms').doc(roomData._id).update({
        members: updatedMembers,
        updateTime: Date.now()
      });
      
      await transaction.collection('game_records').add(recordData);
      
      await transaction.commit();
      
      return {
        code: 0,
        msg: '支付成功',
        data: {
          members: updatedMembers,
          record: recordData
        }
      };
    } catch (e) {
      await transaction.rollback();
      throw e;
    }
  } catch (e) {
    console.error(e);
    return {
      code: -1,
      msg: '支付失败'
    };
  }
}

// 结算房间
async function settleRoom(data) {
  const { roomId } = data;
  console.log('结算房间，roomId:', roomId);
  
  try {
    const room = await rooms.where({
      roomId: roomId,
      status: 0
    }).get();
    
    if (room.data.length === 0) {
      return {
        code: -1,
        msg: '房间不存在或已结束'
      };
    }
    
    const roomData = room.data[0];
    
    // 使用事务确保数据一致性
    const transaction = await db.startTransaction();
    try {
      // 更新房间状态为已结算
      await transaction.collection('rooms').doc(roomData._id).update({
        status: 1,
        settleTime: Date.now(),
        updateTime: Date.now()
      });
      
      // 更新游戏记录状态
      await transaction.collection('game_records').where({
        roomId: roomId,
        status: 0
      }).update({
        status: 1,
        updateTime: Date.now()
      });
      
      // 提交事务
      await transaction.commit();
      
      return {
        code: 0,
        msg: '结算成功',
        data: {
          ...roomData,
          status: 1
        }
      };
    } catch (e) {
      // 回滚事务
      await transaction.rollback();
      throw e;
    }
  } catch (e) {
    console.error('结算房间失败:', e);
    return {
      code: -1,
      msg: '结算失败'
    };
  }
} 